package com.zycoin.common.plugin.mybatis;

import com.zycoin.common.plugin.mybatis.page.TPageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;

/**
 * Created by lenovo on 2017/5/16.
 */
@Configuration
@ConditionalOnProperty(prefix = "page.mybatis", name = "dialect")
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MybatisPageConfiguration implements EnvironmentAware {
    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    private RelaxedPropertyResolver resolver;

    @PostConstruct
    public void addPageInterceptor() {

        TPageInterceptor tPageInterceptor = new TPageInterceptor();
        Properties properties =new Properties();
        String dialect = resolver.getProperty("dialect");
        properties.setProperty("dialect",dialect.toLowerCase());
        tPageInterceptor.setProperties(properties);
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            sqlSessionFactory.getConfiguration().addInterceptor(tPageInterceptor);
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        resolver = new RelaxedPropertyResolver(environment, "page.mybatis.");
    }
}
